//
//  TagListView.swift
//  HelloTagListView
//
//  Created by Chen,Meisong on 2020/11/7.
//

import UIKit
import SnapKit

class TagListView: UIView {
    // MARK: Data
    private var datas: [String]?
    
    // MARK: View
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.estimatedItemSize = CGSize(width: 1, height: 1)
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.register(TagCell.self, forCellWithReuseIdentifier: Constants.cellIdentifier)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = .white
        
        return collectionView
    } ()
    
    // MARK: Init
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubViews()
        makeLayout()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension TagListView {
    // MARK: Constants
    private struct Constants {
        static let cellIdentifier = "cellIdentifier"
    }
}

// MARK: - Layout
extension TagListView {
    private func addSubViews() {
        addSubview(collectionView)
    }
    private func makeLayout() {
        collectionView.snp.makeConstraints { (maker) in
            maker.edges.equalTo(self)
        }
    }
}

extension TagListView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        guard let datas = datas else { return 0 }
        
        return datas.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.cellIdentifier, for: indexPath) as! TagCell
        cell.configData(datas?[indexPath.row])
        
        return cell
    }
}

extension TagListView {
    public func configDatas(_ datas: [String]?) {
        self.datas = datas
        collectionView.reloadData()
    }
}
